import java.util.LinkedList;
import java.util.List;

public class SlidingWindow {
    public static void main(String[] args) {
        System.out.println(totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4}));
    }

    public static int totalFruit(int[] fruits) {
        int n = fruits.length;
        int[] arr = new int[n];//每种类型是否有水果
        int max = 0;
        int count = 0;//记录类型种类
        for (int left = 0, right = 0; right < n; right++) {
            int typeRight = fruits[right];
            if (arr[typeRight] == 0) {
                count++;
            }
            arr[typeRight]++;
            while (count > 2) {
                arr[fruits[left]]--;
                if (arr[fruits[left]] == 0) {
                    count--;
                }
                left++;
            }
            max = Math.max(max, right - left + 1);
        }
        return max;
    }

    public static int totalFruit1(int[] fruits) {
        int n = fruits.length;
        int max = 0;
        List<Integer> list = new LinkedList<>();
        int left = 0, right = 0;
        for (; right < n; right++) {
            if (!list.contains(fruits[right])) {//list不包含这个水果类型
                list.add(fruits[right]);
            }
            while (list.size() > 2) {
                int type = list.get(0);
                if (fruits[left] == type) {
                    left++;
                } else {
                    list.remove(0);
                }
            }
//            max = Math.max(max, right - left + 1);
        }
        return right - left - 1;
    }
}
